package com.oocl.util;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.asm.TypeReference;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.oocl.dto.MerchantDTO;
import com.oocl.vo.MerchandiseVO;

/**
 * @description： Object 与 json 互相转换
 * @author XIEMI2
 * @date Jul 28, 2017 2:33:18 PM
 * @version 1.0
 */
public class JsonUtil {
	private static ObjectMapper mapper = new ObjectMapper();

	/**
	 * Method that can be used to serialize any Java value as a String
	 * @param obj
	 * @return
	 */
	public static String parserToString(Object obj){
		try {
			return mapper.writeValueAsString(obj);
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
		return null;

	}

	/**
	 * Method to deserialize JSON content from given JSON content String
	 * @param json
	 * @param valueType
	 * @return
	 */
	public static <T> Object parserToDTO(String json, Class<T> valueType) {
		 try {
			return mapper.readValue(json, valueType);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return valueType;
	}

	public static List<MerchantDTO> parserToDTOs(String json) throws JsonParseException, JsonMappingException, IOException{
		List<MerchantDTO> merchantDTOs = new ArrayList<MerchantDTO>();
		JavaType javaType = getCollectionType(ArrayList.class, MerchantDTO.class); 
		merchantDTOs = mapper.readValue(json, javaType);
		return merchantDTOs;
	}

	
	 /**   
     * 获取泛型的Collection Type  
     * @param collectionClass 泛型的Collection   
     * @param elementClasses 元素类   
     * @return JavaType Java类型   
     * @since 1.0   
     */   
	 public static JavaType getCollectionType(Class<?> collectionClass, Class<?>... elementClasses) {   
	     return mapper.getTypeFactory().constructParametricType(collectionClass, elementClasses);   
	 }
	 
		public static String parserMerchandiseVOToString(Map<String, MerchandiseVO>  merchandiseVOMap) throws JsonProcessingException {
			String jsonStr = null;
			jsonStr = mapper.writeValueAsString(merchandiseVOMap);

			return jsonStr;
		}
}
